/**
 * desc: 异常处理中间件
 * User: zhitao.guo@leweipai.cn
 * Date: 2020/12/30
 * Time: 12:25
 */
const { HttpException } = require('../core/http-exception')
const { logger } = require('.//log4js')

const catchError = async (ctx, next)=>{
    try {
        await next()
    } catch (error) {
        // 开发环境 不是HttpException
        const isHttpException = error instanceof HttpException
        const isDev = global.config.environment === 'development'
        console.log('catchError', error)
        logger.error(error)
        if(isDev && !isHttpException){
            throw error
        }
        if(isHttpException){
            ctx.body = {
                msg: error.msg,
                code: error.errorCode,
                request:`${ctx.method} ${ctx.path}`
            }
            ctx.status = error.code
        }
        else{
            ctx.body = {
                msg: '服务器异常，请联系开发人员',
                code: 999,
                request:`${ctx.method} ${ctx.path}`
            }
            ctx.status = 500
        }
    }
}

module.exports = catchError;
